package com.itheima.filter;

import com.aliyuncs.utils.StringUtils;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import java.io.IOException;

//@WebFilter("/*")
@Slf4j
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        //1. 获取请求url
        String requestURI = req.getRequestURI();
        log.info("拦截的请求：{}", requestURI);

        //2. 判断如果路径是登录，直接放行
        if (requestURI.contains("/login")) {
            log.info("登录请求，放行");
            //放行，执行controller代码或者下一个过滤器
            chain.doFilter(request, response);
            return;
        }

        //3. 获取token
        String token = req.getHeader("token");

        //4. 如果token为空，直接返回401
        if (StringUtils.isEmpty(token)) {
            log.warn("请求头token为空");
            res.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }

        //5. 解析token，如果解析失败 返回401
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Object id = claims.get("id");
            log.info("校验通过，当前登录用户id：{}", id);
            //存入ThreadLocal中
        } catch (Exception e) {
            res.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        //6. 放行
        chain.doFilter(request, response);

        //从ThreadLocal中移除数据

    }
}
